<?php

namespace App\Http\Controllers\V1\Upload;

use App\Models\V1\Clothes;
use Illuminate\Http\Request;
use App\Http\Requests\V1\ImportDataRequest;
use Maatwebsite\Excel\Facades\Excel;
use App\Events\V1\ImportExportEvent;
use Jenssegers\Agent\Agent;
use Illuminate\Support\Facades\Auth;
use Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use App\Models\V1\ApplyDorms;
use App\Models\V1\NewStudent;
use App\Models\V1\ClotheSize;
use App\Models\V1\ResultClothes;
use App\Models\V1\NewArrival;

class UniformExcelUploadController extends BaseExcelUploadController
{
    
    /**
     * 导出校服信息汇总数据
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $arrival_code = $this->getArrivalCodes();
        
        $clientIP = $request->getClientIp();

        $header = ['校服名称', '校服尺寸', '人均校服数量', '校服总数', '数量单位', '性别限制', '男生人数', '女生人数', '评论'];
        $cellDatas = [$header];
        
        $sql =  'select ClotheSize.id as ClotheSizeId,Clothe.code as ClotheCode,Clothe.name as ClotheName,'
                . 'ClotheSize.code as ClotheSizeCode,ClotheSize.name as ClotheSizeName from basic_clothe_size'
                . ' as ClotheSize join basic_clothes as Clothe on ClotheSize.cloth_code = Clothe.code and '
                . 'ClotheSize.arrival_code = '.$arrival_code
                . ' and Clothe.arrival_code = '.$arrival_code;
        $data = \DB::select(\DB::raw($sql));
        $collection = new Collection($data);
        //定义一下每页显示多少个数据
        $page = 1;
        $perPage = 100;
        //获取当前需要显示的数据列表
        $currentPageSearchResults = $collection->slice(($page-1) * $perPage, $perPage)->all();
        //创建一个新的分页方法
        $paginatedSearchResults= new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
        
        $formatList = array();
        foreach ($paginatedSearchResults->items() as $item) {
            $formatItem['ClotheCode'] = $item->ClotheCode;
            $formatItem['ClotheName'] = $item->ClotheName;
            $formatItem['ClotheSizeCode'] = $item->ClotheSizeCode;
            $formatItem['ClotheSizeName'] = $item->ClotheSizeName;
            // 根据衣服code获取该件衣服相关信息
            $ClotheData = Clothes::where('code', $item->ClotheCode)->where('arrival_code', $arrival_code)->first();
            $formatItem['remark'] = $ClotheData->remark;
            $formatItem['count'] = $ClotheData->count;
            $formatItem['unit'] = $ClotheData->unit;
            $formatItem['sex_limit'] = $ClotheData->sex_limit == 1 ? '男女不限' : ($ClotheData->sex_limit == 2 ? '男生领用' : '女生领用');

            // 计算该衣服下的男生和女生人数
            $boy_count = 0;
            $girl_count = 0;
            $StudentData = NewStudent::where('arrival_code', 'like' , '%'.$arrival_code.'%')->get();
            // 获取当前学期下的学生exam_code集合
            $StudentExamCode = array();
            if(!empty($StudentData)){
                for($i=0;$i<count($StudentData);$i++){
                    $StudentExamCode[] = $StudentData[$i]->exam_code;
                }
            }
            $ResultClothes = ResultClothes::whereIn('exam_code', $StudentExamCode)->where('cloth_code', $item->ClotheCode)->where('size_code', $item->ClotheSizeCode)->get();
            if(!empty($ResultClothes)){
                for($i=0;$i<count($ResultClothes);$i++){
                    $exam_code = $ResultClothes[$i]->exam_code;
                    $StudentInfo = NewStudent::where('exam_code', $exam_code)->first();
                    if(!empty($StudentInfo)){
                        if($StudentInfo->sex == 1){
                            $boy_count++;
                        }elseif($StudentInfo->sex == 2){
                            $girl_count++;
                        }
                    }
                }
            }

            $formatItem['boy_count'] = $boy_count * $formatItem['count'];
            $formatItem['girl_count'] = $girl_count * $formatItem['count'];
            $formatItem['count_sum'] = $formatItem['boy_count'] + $formatItem['girl_count'];
            array_push($formatList, $formatItem);
        }
        
        
        foreach ($formatList as $item) {
            $cellData = [
                $item['ClotheName'],
                $item['ClotheSizeName'],
                $item['count'],
                $item['count_sum'],
                $item['unit'],
                $item['sex_limit'],
                $item['boy_count'],
                $item['girl_count'],
                $item['remark'],
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create(iconv('UTF-8', 'GBK','校服信息汇总'), function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('uniform', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[校服信息汇总]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }
    
    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn',true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }
}
